import {guid, isEmpty} from '@/utils/CommonUtils';
import router from '@/router';
import {ElMessage} from 'element-plus';

export default {
  windows: [],
  timeInterval: null,
  install(Vue) {
    Vue.config.globalProperties.$windowManager = this;
  },

  open(url, config) {
    if (this.checkDuplicate(url)) return;
    this.initConfig(config);
    config.url = url;
    let w = this.createWindow(url, config);
    this.addWindow(w, config);
  },

  checkDuplicate(url) {
    let list = this.windows;
    if (isEmpty(list)) return;
    for (let i = 0; i < list.length; i++) {
      if (list[i].window.closed) continue;
      if (list[i].config.url === url) {
        list[i].window.focus();
        ElMessage({
          showClose: true,
          message: '请勿重复打开窗口',
          type: 'warning',
          appendTo: list[i].window.document.body,
        });
        return true;
      }
    }
    return false;
  },

  createWindow(url, config) {
    let id = guid();
    let w = window.open(url,
      id, 'toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
    // id,);
    w.onload = () => {
      config.onload(w);

      w.onbeforeunload = () => {
        config.onbeforeunload();
      };

      if (config.title) {
        w.document.title = config.title;
      }
    };


    this.bindWindowEvent(config, w);
    return w;
  },

  openWithMenu(menuItem) {
    this.toPath(menuItem);
  },

  toPath(menuItem) {
    let path = menuItem.path;
    path = this.resolvePath(path, menuItem);
    if (menuItem.actionTarget === 'new') {
      this.open(path, {});
    } else {
      router.push(path);
    }
  },

  resolvePath(path, menuItem) {
    if (path.endsWith('/')) {
      return path;
    }
    let params = [];
    if (menuItem.fullScreen + '' === '1') {
      params.push('fullScreen=1');
    }
    params.push(`menuId=${menuItem.id}`);
    if (path.indexOf('?') !== -1) {
      path += '&' + params.join('&')
    } else {
      path += '?' + params.join('&')
    }
    return path;
  },

  bindMethod(methodName, method) {
    window[methodName] = method;
  },
  bindWindowEvent(config, window) {
    let defaultConfig = this.getDefaultConfig();
    for (const key in config) {
      if (!defaultConfig[key]) {
        window[key] = config[key];
      }
    }
  },

  addWindow(window, config) {
    let res = {window, config};
    this.windows.push(res);
    this.startTimeInterval();
    return res;
  },

  startTimeInterval() {
    if (this.timeInterval) return;
    this.timeInterval = setInterval(() => {
      this.checkClose();
    }, 500);
  },

  checkClose() {
    let list = this.windows;
    if (!list || list.length <= 0) return;
    let temp = [];
    for (let i = 0; i < list.length; i++) {
      let item = list[i];
      let {window, config} = item;
      if (window.closed) {
        config.close();
      } else {
        temp.push(item);
      }
    }
    this.windows = temp;
  },

  initConfig(config) {
    let defaultConfig = this.getDefaultConfig();
    for (const key in defaultConfig) {
      if (!config[key]) {
        config[key] = defaultConfig[key];
      }
    }
  },
  emit(methodName, data) {
    // console.log(window, window[methodName], methodName)
    if (window[methodName]) {
      window[methodName](data);
    }
  },
  close(windowId) {
    if (!windowId) {
      window.close();
    }
  },
  getDefaultConfig() {
    return {
      close() {
      },
      onbeforeunload() {
      },
      onload(w) {
      }
    };
  },
};
